//
//  AppDelegate+Add_Update.m
//  ChengHuiTong
//
//  Created by CHT-Technology on 2017/1/11.
//  Copyright © 2017年 张文权. All rights reserved.
//

#import "AppDelegate+Add_Update.h"
#import <objc/runtime.h>
#import "CALayer+Anim.h"

static const void *FullScreenBackGroundView = &FullScreenBackGroundView;

#pragma mark -- 启动广告
@interface LaunchVC : UIViewController{
    
    BOOL _hasGoAdd;
}

@property (nonatomic,copy)void(^ dismissBlock)();

@end
@implementation LaunchVC

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self addAdvertisement];
}

/**
 添加广告视图
 */
- (void)addAdvertisement{
    
    //背景图
    CGRect rect = [UIScreen mainScreen].bounds;
    NSArray *array = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    UIImage *launchImage;
    for (NSDictionary *dic in array) {
        
        if ([NSStringFromCGSize(rect.size) isEqualToString:dic[@"UILaunchImageSize"]]) {
            
            launchImage = [UIImage imageNamed:dic[@"UILaunchImageName"]];
            
            break;
        }
        
    }
    UIImageView* _launchImaViewO = [[UIImageView alloc] initWithFrame:rect];
    _launchImaViewO.userInteractionEnabled = YES;
    _launchImaViewO.image = launchImage;
    [self.view addSubview:_launchImaViewO];
    
    
    //广告图
    NSString *urlString = [[NSUserDefaults standardUserDefaults] objectForKey:@"StartAdvertisementImageUrl"];
    UIImageView *_launchImaViewT = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - autoScaleH(130))];
    _launchImaViewT.backgroundColor = [UIColor whiteColor];
    _launchImaViewT.contentMode = UIViewContentModeScaleAspectFill;
    _launchImaViewT.clipsToBounds = YES;
    _launchImaViewT.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCallBack)];
    [_launchImaViewT addGestureRecognizer:tap];
    [_launchImaViewT sd_setImageWithURL:[NSURL URLWithString:urlString]];
    [_launchImaViewO addSubview:_launchImaViewT];
    
    
    int time = [[[NSUserDefaults standardUserDefaults]objectForKey:@"StartAdvertisementshowTime"] intValue];
    
    //添加跳过按钮
    UIButton *skipBtn = [UIButton creatWithFrame:CGRectMake(SCREEN_WIDTH - 85, 25, 70, 30)
                                            font:[UIFont systemFontOfSize:14]
                                            text:[NSString stringWithFormat:@"跳过 %ds",time]
                                          action:@selector(dismiss)
                                          target:self];
    skipBtn.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.5];
    ViewRadius(skipBtn, 5.f);
    [_launchImaViewT addSubview:skipBtn];
    
    [UIViewController openTimerWithLimit:time progressBlock:^(NSString *seconds) {
        
        [skipBtn setTitle:[NSString stringWithFormat:@"跳过 %@s",seconds] forState:0];
    } completeBlock:^{
        [skipBtn setTitle:@"跳过" forState:0];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (!_hasGoAdd) {
            [self dismiss];
        }
        
    });
}

- (void)dismiss{
    
    _hasGoAdd = YES;
    if (self.dismissBlock) {
        [APPDelegate.window.layer fade];
        self.dismissBlock();
    }
    
}

/**
 广告点击
 */
- (void)tapCallBack{
    NSString *urlStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"StartAdvertisementLinkUrl"];
    if (!urlStr || urlStr.length == 0) {
        return;
    }
    _hasGoAdd = YES;
//    WebViewVC *webVC = [WebViewVC new];
//    webVC.urlString = [[NSUserDefaults standardUserDefaults] objectForKey:@"StartAdvertisementLinkUrl"];
//    webVC.backBlock = ^{
//        [self dismiss];
//    };
//    BaseNavigationController *nav = [[BaseNavigationController alloc]initWithRootViewController:webVC];
//    [webVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
//    [self presentViewController:nav animated:YES completion:nil];
    UIView *bgView = objc_getAssociatedObject(APPDelegate, FullScreenBackGroundView);
    if (bgView) {
        objc_removeAssociatedObjects(bgView);
        [bgView removeAllSubviews];
        [bgView removeFromSuperview];
    }
    [self dismiss];
    YPGoWebView(urlStr, APPDelegate.mainTabbar.viewControllers[0]);
    
}

@end








#pragma mark -- AppDelegate
@interface AppDelegate ()

@property (nonatomic,strong)UIView *bgView;

@end

@implementation AppDelegate (Add_Update)

- (UIView *)bgView{
    
    UIView *bgView = objc_getAssociatedObject(self, FullScreenBackGroundView);
    if (bgView == nil) {
        bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        self.bgView = bgView;
    }
    
    return bgView;
}

- (void)setBgView:(UIView *)bgView{
    
    objc_setAssociatedObject(self, FullScreenBackGroundView, bgView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

/**
 添加广告,检查更新
 */
- (void)requestAdvertisementAndUpdate{
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    //本地有储存图片，则添加广告
    BOOL shouldAddAd = ([userDefault objectForKey:@"StartAdvertisementImageUrl"] && [[userDefault objectForKey:@"StartAdvertisementImageUrl"] length] > 0)?YES:NO;
    if (shouldAddAd){
        
        LaunchVC *launchVC = [[LaunchVC alloc]init];
        launchVC.dismissBlock = ^{
            self.window.rootViewController = self.mainTabbar;
        };
        self.window.rootViewController = launchVC;
    }
    
    
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    [YPHttpRequestMethod sendAsyRequestURL:YPLaunchInit_URL withData:@{@"version":app_Version,@"channel":@"0"} withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        self.dataDic = responseDictionary;
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"AppLaunchRequested" object:nil];
        
        if ([responseDictionary.allKeys containsObject:@"ad_start"]) { //有广告
            
            [userDefault setObject:responseDictionary[@"ad_start"][@"image_url"] forKey:@"StartAdvertisementImageUrl"];
            [userDefault setObject:responseDictionary[@"ad_start"][@"link_url"] forKey:@"StartAdvertisementLinkUrl"];
            [userDefault setObject:responseDictionary[@"ad_start"][@"show_time"] forKey:@"StartAdvertisementshowTime"];
            [userDefault synchronize];
        }else{
            [userDefault removeObjectForKey:@"StartAdvertisementImageUrl"];
            [userDefault removeObjectForKey:@"StartAdvertisementLinkUrl"];
            [userDefault removeObjectForKey:@"StartAdvertisementshowTime"];
            [userDefault synchronize];
        }
        if ([responseDictionary.allKeys containsObject:@"ad_home"]) { //首页弹窗广告

            [self showHomeAdvertisementWithDataDic:responseDictionary[@"ad_home"]];
            
        }
        if ([responseDictionary.allKeys containsObject:@"update"]) { //有更新

            [self showUpDateWithDataDic:responseDictionary[@"update"]];
        
        }
        if ([responseDictionary.allKeys containsObject:@"icon_template"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ChangeTabbarIconNotification object:responseDictionary[@"icon_template"]];
        }
        
    } withFailedBlock:^(NSError *error) {
        
    } withIndicator:NO atView:nil];
    
}

/**
 弹出更新视图
 */
- (void)showUpDateWithDataDic:(NSDictionary *)dic{
    
    
    if ([self configPopUpView]) {
        
        UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(autoScaleW(30), 0, SCREEN_WIDTH - autoScaleW(30)*2, 285)];
        contentView.backgroundColor = [UIColor whiteColor];
        contentView.layer.cornerRadius = 18;
        contentView.layer.masksToBounds = YES;
        [self.bgView addSubview:contentView];
        
        UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(-1, 0, contentView.width+1, 120)];
        imageV.image = [UIImage imageNamed:@"newUpdate"];
        [contentView addSubview:imageV];
        
        UILabel *titleLabel = [UILabel creatWithFrame:CGRectMake(autoScaleW(15), imageV.bottom, contentView.width - autoScaleW(15)*2, 30)
                                                 font:[UIFont systemFontOfSize:16]
                                                 text:@"更新说明:"
                                            textColor:[UIColor blackColor]
                                        textAlignment:0];
        [contentView addSubview:titleLabel];
        
        UILabel*contentLabel = [UILabel creatWithFrame:CGRectMake(titleLabel.left, titleLabel.bottom, contentView.width - autoScaleW(15)*2, 80)
                                                  font:[UIFont systemFontOfSize:14]
                                                  text:dic[@"summary"]
                                             textColor:kColor_greyAshTitleColor
                                         textAlignment:0];
        CGFloat height = [contentLabel.text heightWithFont:contentLabel.font width:contentLabel.width];
        contentLabel.height = MAX(height, contentLabel.height);
        contentLabel.numberOfLines = 0;
        [contentView addSubview:contentLabel];
        
        [contentView addLineWithFrame:CGRectMake(0, contentLabel.bottom + 10, contentView.width, 1) color:colorWithRGB(230, 230, 230)];
        
        if ([dic[@"opinion"] integerValue] == 0) { //建议更新
            
            UIButton *btn = [UIButton creatWithFrame:CGRectMake(0, contentLabel.bottom + 10, contentView.width/2.f, 45)
                                                font:[UIFont systemFontOfSize:18]
                                                text:@"忽略"
                                           textColor:[UIColor grayColor]
                                              action:@selector(removePopupViews)
                                              target:self];
            [contentView addSubview:btn];
            
            UIButton *btn1 = [UIButton creatWithFrame:CGRectMake(btn.right, btn.top, btn.width, btn.height)
                                                 font:btn.titleLabel.font
                                                 text:@"立即更新"
                                            textColor:kColor_AppNavColor
                                               action:@selector(gotoUpdate:)
                                               target:self];
            [contentView addSubview:btn1];
            
            [btn addLineWithFrame:CGRectMake(btn.width-1, 0, 1, btn.height) color:colorWithRGB(230, 230, 230)];
            
            contentView.height = btn.bottom;
        }else{ //强制更新
            
            UIButton *btn1 = [UIButton creatWithFrame:CGRectMake(0, contentLabel.bottom + 10, contentView.width, 45)
                                                 font:[UIFont systemFontOfSize:18]
                                                 text:@"立即更新"
                                            textColor:kColor_AppNavColor
                                               action:@selector(gotoUpdate:)
                                               target:self];
            [contentView addSubview:btn1];
            
            contentView.height = btn1.bottom;
        }
        
        contentView.center = self.bgView.center;
        
    }
    
    
}

/**
 弹出首页广告
 */
- (void)showHomeAdvertisementWithDataDic:(NSDictionary *)dic{
    
    if ([self configPopUpView]) {
        
        UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(20, 40, SCREEN_WIDTH - 40, SCREEN_HEIGHT - 20)];
        contentView.center = self.bgView.center;
        contentView.backgroundColor = [UIColor clearColor];
        contentView.layer.masksToBounds = YES;
        [self.bgView addSubview:contentView];
        
        
        UIImageView *imageV = [[UIImageView alloc]initWithFrame:contentView.bounds];
        imageV.contentMode = UIViewContentModeScaleAspectFit;
        imageV.userInteractionEnabled = YES;
        [imageV sd_setImageWithURL:[NSURL URLWithString:dic[@"image_url"]]];
        [contentView addSubview:imageV];
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gotoHomeAdd:)];
        [imageV addGestureRecognizer:tap];
        
        
        
        UIButton *closeBtn = [UIButton creatWithFrame:CGRectMake(self.bgView.width - 40, 20, 40, 40)
                                                image:[UIImage imageNamed:@"btn1_nor"]
                                               action:@selector(removePopupViews)
                                               target:self];
        [self.bgView addSubview:closeBtn];
    }

}

/**
 配置弹框视图
 */
- (BOOL)configPopUpView{
    
    if(self.mainTabbar.selectedIndex != 0 || [[(UINavigationController *)self.mainTabbar.viewControllers.firstObject viewControllers ] count] > 1) return NO;
    
    if(![self.mainTabbar.view.subviews containsObject:self.bgView])
        [self.mainTabbar.view addSubview:self.bgView];
    
    return YES;
}

/**
 跳转更新
 */
- (void)gotoUpdate:(UIButton *)btn{
    
    NSString *urlString = self.dataDic[@"update"][@"ios_url"];
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
    }
}

/**
 首页广告跳转
 */
- (void)gotoHomeAdd:(UIGestureRecognizer *)gesture{
    
    UINavigationController *nav = (UINavigationController *)self.mainTabbar.viewControllers.firstObject;

    YPGoWebView(self.dataDic[@"ad_home"][@"link_url"], nav);
    
    [self removePopupViews];
}

/**
 移除弹框视图
 */
- (void)removePopupViews{
    objc_removeAssociatedObjects(self.bgView);
    [self.bgView removeAllSubviews];
    [self.bgView removeFromSuperview];
    
}

@end


